package com.cloud.code.leetcode;

import java.util.ArrayList;
import java.util.List;

public class Demo5 {
    public List<String> generateParenthesis(int n) {

        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        int left = 0;
        int right = 0;
        dfs(res,left,right,n,sb);
        return res;
    }

    private void dfs(List<String> res, int left, int right, int n,StringBuilder sb) {

        if(left == n && right == n){
            res.add(new StringBuilder(sb).toString());
            return;
        }

        if(left < n){
            sb.append("(");
            dfs(res,left+1,right,n,sb);
            sb.deleteCharAt(sb.length()-1);
        }

        if(right < left){
            sb.append(")");
            dfs(res,left+1,right,n,sb);
            sb.deleteCharAt(sb.length()-1);
        }


    }
}
